package com.xinjian.jianba.config;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.xinjian.jianba.es.pool.ElasticSearchPool;
import com.xinjian.jianba.es.pool.ElasticSearchPoolConfig;
import com.xinjian.jianba.es.pool.HostAndPort;

@Configuration
public class ElasticSearchPoolFactory {

	@Autowired
	private ElasticSearchConfig elasticSearchConfig;
	
	@Bean
	public ElasticSearchPool elasticSearchPool(){
		HostAndPort hostPort =null;
		String Hostport=elasticSearchConfig.getHostport();
		if (StringUtils.isNotBlank(Hostport)) {
	            String[] hostAndPort = StringUtils.split(Hostport,":",2);
	            if(hostAndPort.length==2&&Integer.parseInt(hostAndPort[1])>0) {
	            	hostPort=new HostAndPort(hostAndPort[0], Integer.parseInt(hostAndPort[1]),elasticSearchConfig.getUserName(),elasticSearchConfig.getPassword());
	            }
			}
		ElasticSearchPoolConfig elasticSearchPoolConfig=new ElasticSearchPoolConfig();
		elasticSearchPoolConfig.setConnectTimeMillis(elasticSearchConfig.getTimeout()==0?8000:elasticSearchConfig.getTimeout());
		elasticSearchPoolConfig.setMaxTotal(elasticSearchConfig.getMaxTotal()==0?8:elasticSearchConfig.getMaxTotal());
		elasticSearchPoolConfig.setMaxIdle(elasticSearchConfig.getMaxIdle()==0?8:elasticSearchConfig.getMaxIdle());
		elasticSearchPoolConfig.setMinIdle(elasticSearchConfig.getMinIdle());
		elasticSearchPoolConfig.setMaxWaitMillis(elasticSearchConfig.getMaxWaitMillis()==0?-1:elasticSearchConfig.getMaxWaitMillis());
		elasticSearchPoolConfig.setTestOnBorrow(elasticSearchConfig.isTestOnBorrow());
		elasticSearchPoolConfig.setTestWhileIdle(elasticSearchConfig.isTestWhileIdle());
		elasticSearchPoolConfig.setTestOnCreate(elasticSearchConfig.isTestOnCreate());
		elasticSearchPoolConfig.setTestOnReturn(elasticSearchConfig.isTestOnReturn());
		elasticSearchPoolConfig.setNode(hostPort);
		ElasticSearchPool pool = new ElasticSearchPool(elasticSearchPoolConfig);
		return pool;
 }
}
